using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;

namespace MesProject.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class BomController : ControllerBase
    {
        private readonly ApplicationDbContext _context;
        private readonly ILogger<BomController> _logger;

        public BomController(ApplicationDbContext context, ILogger<BomController> logger)
        {
            _context = context;
            _logger = logger;
        }

        /// <summary>
        /// 获取所有BOM信息
        /// </summary>
        /// <returns>BOM列表</returns>
        [HttpGet("GetBoms")]
        public async Task<IActionResult> GetBoms()
        {
            try
            {
                var boms = await _context.Boms
                    .Where(b => !b.IsDeleted)
                    .ToListAsync();

                return Ok(new ApiResult<List<Bommodel>>
                {
                    Code = "200",
                    Message = "获取成功",
                    Data = boms
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取BOM列表时发生错误");
                return StatusCode(500, new ApiResult<object>
                {
                    Code = "500",
                    Message = "获取BOM列表失败: " + ex.Message
                });
            }
        }

        /// <summary>
        /// 根据编码获取BOM信息
        /// </summary>
        /// <param name="bomCode">BOM编码</param>
        /// <returns>符合条件的BOM列表</returns>
        [HttpGet("GetBomsByCode")]
        public async Task<IActionResult> GetBomsByCode(string bomCode = "")
        {
            try
            {
                var query = _context.Boms.Where(b => !b.IsDeleted);
                
                if (!string.IsNullOrEmpty(bomCode))
                {
                    query = query.Where(b => b.Bomcode.Contains(bomCode));
                }
                
                var boms = await query.ToListAsync();

                return Ok(new ApiResult<List<Bommodel>>
                {
                    Code = "200",
                    Message = "获取成功",
                    Data = boms
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据编码获取BOM列表时发生错误");
                return StatusCode(500, new ApiResult<object>
                {
                    Code = "500",
                    Message = "获取BOM列表失败: " + ex.Message
                });
            }
        }

        /// <summary>
        /// 获取BOM详情及其子项
        /// </summary>
        /// <param name="id">BOM ID</param>
        /// <returns>BOM详情及其子项</returns>
        [HttpGet("GetBomDetailWithChildren")]
        public async Task<IActionResult> GetBomDetailWithChildren(long id)
        {
            try
            {
                var bom = await _context.Boms
                    .FirstOrDefaultAsync(b => b.Id == id && !b.IsDeleted);

                if (bom == null)
                {
                    return NotFound(new ApiResult<object>
                    {
                        Code = "404",
                        Message = "未找到指定的BOM记录"
                    });
                }

                // 获取子项（这里需要根据实际数据结构调整）
                var children = await _context.Boms
                    .Where(b => b.ParentId == id && !b.IsDeleted)
                    .ToListAsync();

                return Ok(new ApiResult<object>
                {
                    Code = "200",
                    Message = "获取成功",
                    Data = new
                    {
                        Bom = bom,
                        Children = children
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取BOM详情及子项时发生错误");
                return StatusCode(500, new ApiResult<object>
                {
                    Code = "500",
                    Message = "获取BOM详情失败: " + ex.Message
                });
            }
        }

        /// <summary>
        /// 添加BOM信息
        /// </summary>
        /// <param name="bom">BOM对象</param>
        /// <returns>操作结果</returns>
        [HttpPost("AddBom")]
        public async Task<IActionResult> AddBom([FromBody] Bommodel bom)
        {
            if (bom == null)
            {
                return BadRequest(new ApiResult<object>
                {
                    Code = "400",
                    Message = "无效的请求数据"
                });
            }

            try
            {
                // 检查编码是否已存在
                var existingBom = await _context.Boms
                    .FirstOrDefaultAsync(b => b.Bomcode == bom.Bomcode && !b.IsDeleted);

                if (existingBom != null)
                {
                    return BadRequest(new ApiResult<object>
                    {
                        Code = "400",
                        Message = "BOM编码已存在"
                    });
                }

                // 设置创建时间和更新时间
                bom.CreatedTime = DateTime.Now;
                bom.UpdatedTime = DateTime.Now;
                bom.IsDeleted = false;

                // 添加到数据库
                _context.Boms.Add(bom);
                await _context.SaveChangesAsync();

                return Ok(new ApiResult<Bommodel>
                {
                    Code = "200",
                    Message = "添加成功",
                    Data = bom
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加BOM时发生错误");
                return StatusCode(500, new ApiResult<object>
                {
                    Code = "500",
                    Message = "添加BOM失败: " + ex.Message
                });
            }
        }

        /// <summary>
        /// 更新BOM信息
        /// </summary>
        /// <param name="id">BOM ID</param>
        /// <param name="bom">更新后的BOM对象</param>
        /// <returns>操作结果</returns>
        [HttpPut("UpdateBom")]
        public async Task<IActionResult> UpdateBom(long id, [FromBody] Bommodel bom)
        {
            if (bom == null || id <= 0)
            {
                return BadRequest(new ApiResult<object>
                {
                    Code = "400",
                    Message = "无效的请求数据"
                });
            }

            try
            {
                // 查找要更新的BOM记录
                var existingBom = await _context.Boms
                    .FirstOrDefaultAsync(b => b.Id == id && !b.IsDeleted);

                if (existingBom == null)
                {
                    return NotFound(new ApiResult<object>
                    {
                        Code = "404",
                        Message = "未找到指定的BOM记录"
                    });
                }

                // 检查编码是否已被其他记录使用
                if (bom.Bomcode != existingBom.Bomcode)
                {
                    var codeExists = await _context.Boms
                        .AnyAsync(b => b.Bomcode == bom.Bomcode && b.Id != id && !b.IsDeleted);

                    if (codeExists)
                    {
                        return BadRequest(new ApiResult<object>
                        {
                            Code = "400",
                            Message = "BOM编码已被其他记录使用"
                        });
                    }
                }

                // 更新BOM属性
                existingBom.Bomcode = bom.Bomcode;
                existingBom.Bomname = bom.Bomname;
                existingBom.Bomversion = bom.Bomversion;
                existingBom.Bomdescription = bom.Bomdescription;
                existingBom.BomType = bom.BomType;
                existingBom.Bomranks = bom.Bomranks;
                existingBom.UpdatedTime = DateTime.Now;
                existingBom.UpdatedBy = bom.UpdatedBy;
                
                // 如果有其他需要更新的字段，也一并更新
                existingBom.Processmanagementcode = bom.Processmanagementcode;
                existingBom.Processmanagementname = bom.Processmanagementname;
                existingBom.Bomdosage = bom.Bomdosage;

                // 保存更改
                await _context.SaveChangesAsync();

                return Ok(new ApiResult<Bommodel>
                {
                    Code = "200",
                    Message = "更新成功",
                    Data = existingBom
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新BOM时发生错误");
                return StatusCode(500, new ApiResult<object>
                {
                    Code = "500",
                    Message = "更新BOM失败: " + ex.Message
                });
            }
        }

        /// <summary>
        /// 软删除BOM记录
        /// </summary>
        /// <param name="id">BOM ID</param>
        /// <returns>操作结果</returns>
        [HttpPut("SoftDeleteBom")]
        public async Task<IActionResult> SoftDeleteBom(long id)
        {
            try
            {
                // 查找要删除的BOM记录
                var bom = await _context.Boms
                    .FirstOrDefaultAsync(b => b.Id == id && !b.IsDeleted);

                if (bom == null)
                {
                    return NotFound(new ApiResult<object>
                    {
                        Code = "404",
                        Message = "未找到指定的BOM记录"
                    });
                }

                // 软删除（设置IsDeleted标志）
                bom.IsDeleted = true;
                bom.UpdatedTime = DateTime.Now;

                // 保存更改
                await _context.SaveChangesAsync();

                return Ok(new ApiResult<object>
                {
                    Code = "200",
                    Message = "删除成功"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除BOM时发生错误");
                return StatusCode(500, new ApiResult<object>
                {
                    Code = "500",
                    Message = "删除BOM失败: " + ex.Message
                });
            }
        }
    }

    // API结果包装类
    public class ApiResult<T>
    {
        public string Code { get; set; }
        public string Message { get; set; }
        public T Data { get; set; }
    }
} 